package cn.com.lsy.product.lepao.controller;

import cn.com.lsy.product.lepao.common.Constant;
import cn.com.lsy.product.lepao.controller.base.BaseController;
import cn.com.lsy.product.lepao.model.entities.*;
import cn.com.lsy.product.lepao.model.mt.entities.*;
import cn.com.lsy.product.lepao.request.*;
import cn.com.lsy.product.lepao.response.*;
import cn.com.lsy.product.lepao.response.base.ApiResponseEnum;
import cn.com.lsy.product.lepao.response.base.BaseRet;
import cn.com.lsy.product.lepao.response.base.PageInfo;
import cn.com.lsy.product.lepao.service.*;
import cn.com.lsy.product.lepao.util.CommonFunctionUtil;
import cn.com.lsy.product.lepao.util.DozerMapperUtil;
import cn.com.lsy.product.lepao.util.payUtil.aliPayUtil.AlipayUtil;
import com.alipay.api.response.AlipayFundAuthOrderUnfreezeResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "财务管理接口", tags = "财务管理接口")
@RestController
@RequestMapping(value = "/lepao/console/doAuth")
public class FinanceController extends BaseController {

    private Logger log = Logger.getLogger(FinanceController.class);

    @Autowired
    IFinanceService iFinanceService;
    @Autowired
    IUserService iUserService;
    @Autowired
    ISessionService iSessionService;
    @Autowired
    IGoodsService iGoodsService;
    @Autowired
    IDataTotalService iDataTotalService;
    @Autowired
    IStoreService iStoreService;
    @Autowired
    IDeviceService iDeviceService;

    @RequestMapping(value = "/depositList", method = RequestMethod.POST)
    @ApiOperation(notes = "押金列表", httpMethod = "POST", value = "押金列表")
    public BaseRet<PageInfo<List<SearchDepositListRet>>> depositList(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SearchDepositListParam param, BindingResult result) {

        BaseRet<PageInfo<List<SearchDepositListRet>>> ret = new BaseRet<PageInfo<List<SearchDepositListRet>>>();

        PageInfo<List<SearchDepositListRet>> pageInfo = new PageInfo<List<SearchDepositListRet>>();

        try {

            checkParam(result);

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                param.setStartTime(param.getStartTime() + " 00:00:00");
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                param.setEndTime(param.getEndTime() + " 23:59:59");
            }


            List<SearchDepositListRet> listRet = new ArrayList<SearchDepositListRet>();

            int count = iFinanceService.selectDepositByCount(param.getStatus(), param.getStartTime(), param.getEndTime(), param.getSearchCondition());
            pageInfo.setCount(count);
            int start = param.getStart();

            List<SearchDepositListDto> list = iFinanceService.selectDepositByPage(start, param.getPageSize(), param.getStatus(), param.getStartTime(), param.getEndTime(), param.getSearchCondition());

            if (list != null && list.size() > 0) {

                listRet = DozerMapperUtil.mapList(list, SearchDepositListRet.class);

            }

            pageInfo.setRecords(listRet);

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(pageInfo);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/depositRefund", method = RequestMethod.POST)
    @ApiOperation(notes = "押金退回", httpMethod = "POST", value = "押金退回")
    public BaseRet<String> depositRefund(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody DepositRefundParam param, BindingResult result) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            checkParam(result);

            //查询用户token
            List<LpSessionTbl> sessionInfo = iSessionService.selectInfoByUserId(param.getId(), Constant.roleType.app);

            if (sessionInfo != null && sessionInfo.size() > 0) {

                String token = sessionInfo.get(0).getToken();

                //请求接口退押金
                Map<String, String> header = new HashMap<String, String>();
                header.put("Content-Type", "application/json");
                header.put("token", token);
                header.put("roleType", "APP");
                header.put("DEV-ID", "CONSOLE");

                String httpResult = CommonFunctionUtil.sendPost(Constant.httpConfig.apiUrl + "doAuth/DepositRefund", "", header);

                JSONObject httpResultJson = JSONObject.fromObject(httpResult);
                if (httpResultJson.getString("code").equals(ApiResponseEnum.API_RESPONSE_SUCCESS)) {

                    //写入退款原因
                    LpOrderformTbl lpOrderformTbl = new LpOrderformTbl();
                    lpOrderformTbl.setId(param.getOrderId());
                    lpOrderformTbl.setRefundContent(param.getContent());
                    iFinanceService.updateOrder(lpOrderformTbl);

                    ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
                    ret.setMsg("退款成功");

                } else {

                    ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                    ret.setMsg(httpResultJson.getString("msg"));
                }

            } else {

                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                ret.setMsg("用户token无法获取");
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/incomeList", method = RequestMethod.POST)
    @ApiOperation(notes = "收入列表", httpMethod = "POST", value = "收入列表")
    public BaseRet<PageInfo<List<IncomeListRet>>> incomeList(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SearchIncomeListParam param, BindingResult result) {

        BaseRet<PageInfo<List<IncomeListRet>>> ret = new BaseRet<PageInfo<List<IncomeListRet>>>();

        PageInfo<List<IncomeListRet>> pageInfo = new PageInfo<List<IncomeListRet>>();

        try {

            checkParam(result);

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                param.setStartTime(param.getStartTime() + " 00:00:00");
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                param.setEndTime(param.getEndTime() + " 23:59:59");
            }

            if (param.getStoreIdList().size() <= 0) {
                param.setStoreIdList(null);
            }

            List<IncomeListRet> listRet = new ArrayList<IncomeListRet>();

            int count = iFinanceService.selectIncomeByCount(param.getStatus(), param.getStartTime(), param.getEndTime(), param.getSearchCondition(), param.getStoreIdList(), param.getStoreId(), param.getGoodsType());
            pageInfo.setCount(count);
            int start = param.getStart();

            List<IncomeListDto> list = iFinanceService.selectIncomeByPage(start, param.getPageSize(), param.getStatus(), param.getStartTime(), param.getEndTime(), param.getSearchCondition(), param.getStoreIdList(), param.getStoreId(), param.getGoodsType());

            if (list != null && list.size() > 0) {

                for (IncomeListDto value : list) {

                    IncomeListRet incomeListRet = DozerMapperUtil.map(value, IncomeListRet.class);
                    incomeListRet.setBalancePay(BigDecimal.ZERO);
                    String payDetail = value.getPayDetail();
                    if (StringUtils.isNotEmpty(payDetail)) {

                        JSONArray jsonArray = JSONArray.fromObject(payDetail);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject object = jsonArray.getJSONObject(i);
                            if (object.getString("type").equals(Constant.getPayType.balancePay)) {
                                incomeListRet.setBalancePay(new BigDecimal(object.getString("price")));
                                break;
                            }
                        }
                    }

                    incomeListRet.setPayType(CommonFunctionUtil.getPayType(value.getPayType()));

                    listRet.add(incomeListRet);

                }
            }

            pageInfo.setRecords(listRet);

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(pageInfo);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/incomeSum", method = RequestMethod.POST)
    @ApiOperation(notes = "收入汇总", httpMethod = "POST", value = "收入汇总")
    public BaseRet<BigDecimal> incomeSum(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SearchIncomeListParam param, BindingResult result) {

        BaseRet<BigDecimal> ret = new BaseRet<BigDecimal>();

        try {

            checkParam(result);

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                param.setStartTime(param.getStartTime() + " 00:00:00");
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                param.setEndTime(param.getEndTime() + " 23:59:59");
            }

            if (param.getStoreIdList().size() <= 0) {
                param.setStoreIdList(null);
            }

            BigDecimal sumPrice = iFinanceService.selectIncomeSum(param.getStatus(), param.getStartTime(), param.getEndTime(), param.getSearchCondition(), param.getStoreIdList(), param.getStoreId(), param.getGoodsType());

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(sumPrice);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/depositSum", method = RequestMethod.POST)
    @ApiOperation(notes = "押金未退汇总", httpMethod = "POST", value = "押金未退汇总")
    public BaseRet<BigDecimal> depositSum() {

        BaseRet<BigDecimal> ret = new BaseRet<BigDecimal>();

        try {


            BigDecimal price = iFinanceService.selectDepositSum();

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(price);


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/orderPayInfo", method = RequestMethod.POST)
    @ApiOperation(notes = "订单支付详情", httpMethod = "POST", value = "订单支付详情")
    public BaseRet<OrderPayInfoBaseRet> orderPayInfo(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody ActionLibraryInfoParam param, BindingResult result) {

        BaseRet<OrderPayInfoBaseRet> ret = new BaseRet<OrderPayInfoBaseRet>();

        try {

            checkParam(result);

            OrderPayInfoBaseRet orderPayInfoBaseRet = new OrderPayInfoBaseRet();
            List<OrderPayInfoRet> payInfo = new ArrayList<OrderPayInfoRet>();//支付信息
            List<OrderPayInfoRet> discountInfo = new ArrayList<OrderPayInfoRet>();//优惠信息
            BigDecimal totalPrice = BigDecimal.ZERO;//支付总金额
            BigDecimal discountPrice = BigDecimal.ZERO;//优惠总金额

            OrderPayInfoDto orderInfo = iFinanceService.selectOrderPayInfo(param.getId());

            //处理支付信息
            if (StringUtils.isNotEmpty(orderInfo.getPayDetail())) {

                JSONArray jsonArray = JSONArray.fromObject(orderInfo.getPayDetail());
                for (int i = 0; i < jsonArray.size(); i++) {

                    JSONObject object = jsonArray.getJSONObject(i);

                    if (!object.getString("price").equals("0")) {

                        OrderPayInfoRet orderPayInfoRet = new OrderPayInfoRet();

                        orderPayInfoRet.setPrice(new BigDecimal(object.getString("price")));
                        orderPayInfoRet.setName(CommonFunctionUtil.getPayType(object.getString("type")));
                        payInfo.add(orderPayInfoRet);
                        BigDecimal price = new BigDecimal(object.getString("price"));
                        totalPrice = totalPrice.add(price);
                    }
                }

            }


            //处理优惠信息
            if (StringUtils.isNotEmpty(orderInfo.getDiscountDetail())) {

                JSONArray jsonArray = JSONArray.fromObject(orderInfo.getDiscountDetail());
                for (int i = 0; i < jsonArray.size(); i++) {

                    JSONObject object = jsonArray.getJSONObject(i);

                    if (!object.getString("price").equals("0")) {

                        OrderPayInfoRet orderPayInfoRet = new OrderPayInfoRet();

                        orderPayInfoRet.setPrice(new BigDecimal(object.getString("price")));
                        orderPayInfoRet.setName(CommonFunctionUtil.getDiscountType(object.getString("type")));
                        discountInfo.add(orderPayInfoRet);
                        discountPrice = discountPrice.add(new BigDecimal(object.getString("price")));
                    }
                }

            }

            orderPayInfoBaseRet.setDiscountInfo(discountInfo);
            orderPayInfoBaseRet.setDiscountPrice(discountPrice);
            orderPayInfoBaseRet.setPayInfo(payInfo);
            orderPayInfoBaseRet.setTotalPrice(totalPrice);

            if (StringUtils.isNotEmpty(orderInfo.getCouponName())) {
                orderPayInfoBaseRet.setCouponName(orderInfo.getCouponName());
            } else {
                orderPayInfoBaseRet.setCouponName("未使用优惠劵");
            }

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(orderPayInfoBaseRet);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/balanceList", method = RequestMethod.POST)
    @ApiOperation(notes = "余额列表", httpMethod = "POST", value = "余额列表")
    public BaseRet<PageInfo<List<BalanceListRet>>> balanceList(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody BalanceListParam param, BindingResult result) {

        BaseRet<PageInfo<List<BalanceListRet>>> ret = new BaseRet<PageInfo<List<BalanceListRet>>>();

        PageInfo<List<BalanceListRet>> pageInfo = new PageInfo<List<BalanceListRet>>();

        try {

            checkParam(result);

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                param.setStartTime(param.getStartTime() + " 00:00:00");
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                param.setEndTime(param.getEndTime() + " 23:59:59");
            }

            int count = iFinanceService.selectBalanceByCount(param.getStartTime(), param.getEndTime(), param.getSearchCondition());
            pageInfo.setCount(count);
            int start = param.getStart();

            List<BalanceListDto> list = iFinanceService.selectBalanceByPage(start, param.getPageSize(), param.getStartTime(), param.getEndTime(), param.getSearchCondition());

            if (list != null && list.size() > 0) {

                List<BalanceListRet> listRet = DozerMapperUtil.mapList(list, BalanceListRet.class);
                pageInfo.setRecords(listRet);
            }

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(pageInfo);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/giveList", method = RequestMethod.POST)
    @ApiOperation(notes = "赠送列表", httpMethod = "POST", value = "赠送列表")
    public BaseRet<PageInfo<List<GiveListRet>>> giveList(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody BalanceListParam param, BindingResult result) {

        BaseRet<PageInfo<List<GiveListRet>>> ret = new BaseRet<PageInfo<List<GiveListRet>>>();

        PageInfo<List<GiveListRet>> pageInfo = new PageInfo<List<GiveListRet>>();

        try {

            checkParam(result);

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                param.setStartTime(param.getStartTime() + " 00:00:00");
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                param.setEndTime(param.getEndTime() + " 23:59:59");
            }

            int count = iFinanceService.selectGiveByCount(param.getStartTime(), param.getEndTime(), param.getSearchCondition());
            pageInfo.setCount(count);
            int start = param.getStart();

            List<GiveListDto> list = iFinanceService.selectGiveByPage(start, param.getPageSize(), param.getStartTime(), param.getEndTime(), param.getSearchCondition());

            if (list != null && list.size() > 0) {

                List<GiveListRet> listRet = DozerMapperUtil.mapList(list, GiveListRet.class);
                pageInfo.setRecords(listRet);
            }

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(pageInfo);

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/dayCardRefund", method = RequestMethod.POST)
    @ApiOperation(notes = "次卡退款", httpMethod = "POST", value = "次卡退款")
    public BaseRet<String> dayCardRefund(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody DayCardRefundParam param, BindingResult result) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            checkParam(result);

            //查询用户token
            List<LpSessionTbl> sessionInfo = iSessionService.selectInfoByUserId(param.getUserId(), Constant.roleType.app);

            if (sessionInfo != null && sessionInfo.size() > 0) {

                String token = sessionInfo.get(0).getToken();

                //请求接口退押金
                Map<String, String> header = new HashMap<String, String>();
                header.put("Content-Type", "application/json");
                header.put("token", token);
                header.put("roleType", "APP");
                header.put("DEV-ID", "CONSOLE");

                JSONObject httpParam = new JSONObject();
                httpParam.put("ofId", param.getOrderId());

                String httpResult = CommonFunctionUtil.sendPost(Constant.httpConfig.apiUrl + "doAuth/dayCardRefund", com.alibaba.fastjson.JSONObject.toJSONString(httpParam), header);

                JSONObject httpResultJson = JSONObject.fromObject(httpResult);
                if (httpResultJson.getString("code").equals(ApiResponseEnum.API_RESPONSE_SUCCESS)) {

                    //写入退款原因
                    LpOrderformTbl lpOrderformTbl = new LpOrderformTbl();
                    lpOrderformTbl.setId(param.getOrderId());
                    lpOrderformTbl.setRefundContent(param.getContent());
                    iFinanceService.updateOrder(lpOrderformTbl);

                    ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
                    ret.setMsg("退款成功");

                } else {

                    ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                    ret.setMsg(httpResultJson.getString("msg"));
                }

            } else {

                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                ret.setMsg("用户token无法获取");
            }


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/dataTotal", method = RequestMethod.GET)
    @ApiOperation(notes = "平台数据统计（定时任务调用）", httpMethod = "GET", value = "平台数据统计（定时任务调用）")
    public BaseRet<String> dataTotal(@ApiParam(value = "请求参数", required = true) @RequestParam String setTime) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            //获取当前时间
            String time = CommonFunctionUtil.getStringTime(Constant.formatType.date);

            if (StringUtils.isNotEmpty(setTime)) {
                time = setTime;
            }

            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";
            //新注册用户
            BigDecimal newRegisterTotal = iDataTotalService.selectNewRegisterTotal(startTime, endTime);
            //总入场（需要门店）
            BigDecimal enterTotal = iDataTotalService.selectEnterTotal(startTime, endTime, 0);
            //次卡入场（需要门店）
            BigDecimal DayCardEnterTotal = iDataTotalService.selectDayCardEnterTotal(startTime, endTime, 0);
            //月卡入场（需要门店）
            BigDecimal MonthCardEnterTotal = iDataTotalService.selectMonthCardEnterTotal(startTime, endTime, 0);
            //优惠劵入场（需要门店）
            BigDecimal CouponEnterTotal = iDataTotalService.selectCouponEnterTotal(startTime, endTime, 0);
            //新增月卡
            BigDecimal NewMonthCardTotal = iDataTotalService.selectNewMonthCardTotal(startTime, endTime);
            //交押金
            BigDecimal PaymentDeposit = iDataTotalService.selectPaymentDeposit(startTime, endTime);
            //退押金
            BigDecimal RefundDeposit = iDataTotalService.selectRefundDeposit(startTime, endTime);
            //押金余额
            BigDecimal DepositBalance = iDataTotalService.selectDepositBalance(startTime, endTime);
            //充值金额
            BigDecimal Recharge = iDataTotalService.selectRecharge(startTime, endTime);
            //总收入（需要门店）
            BigDecimal income = iDataTotalService.selectIncome(startTime, endTime, null);
            //次卡收入（需要门店）
            BigDecimal DayCardIncome = iDataTotalService.selectDayCardIncome(startTime, endTime, 0);
            //月卡收入
            BigDecimal MonthCardIncome = iDataTotalService.selectMonthCardIncome(startTime, endTime);

            LpDataTotalTbl lpDataTotalTbl = new LpDataTotalTbl();
            lpDataTotalTbl.setNewRegister(newRegisterTotal);
            lpDataTotalTbl.setEnterTotal(enterTotal);
            lpDataTotalTbl.setDayCardEnterTotal(DayCardEnterTotal);
            lpDataTotalTbl.setMonthCardEnterTotal(MonthCardEnterTotal);
            lpDataTotalTbl.setCouponEnterTotal(CouponEnterTotal);
            lpDataTotalTbl.setNewMonthCardTotal(NewMonthCardTotal);
            lpDataTotalTbl.setPaymentDeposit(PaymentDeposit);
            lpDataTotalTbl.setRefundDeposit(RefundDeposit);
            lpDataTotalTbl.setDepositBalance(DepositBalance);
            lpDataTotalTbl.setRecharge(Recharge);
            lpDataTotalTbl.setIncome(income);
            lpDataTotalTbl.setTimes(CommonFunctionUtil.changeTimeDate(time, Constant.formatType.date));
            lpDataTotalTbl.setInsertTime(CommonFunctionUtil.getDateTime(Constant.formatType.second));
            lpDataTotalTbl.setDaycardIncome(DayCardIncome);
            lpDataTotalTbl.setMonthcardIncome(MonthCardIncome);

            //查询当天是否已经写入了
            List<LpDataTotalTbl> list = iDataTotalService.selectDataTotal(CommonFunctionUtil.changeTimeDate(time, Constant.formatType.date));

            if (list != null && list.size() > 0) {

                //删除原有数据
                iDataTotalService.delDataTotal(list.get(0).getId());

            }

            //写入数据
            if (iDataTotalService.addDataTotal(lpDataTotalTbl) > 0) {

                ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
                ret.setMsg("写入成功");

            } else {

                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                ret.setMsg("写入失败");
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/dataTotalList", method = RequestMethod.POST)
    @ApiOperation(notes = "数据统计列表", httpMethod = "POST", value = "数据统计列表")
    public BaseRet<PageInfo<List<DataTotalRet>>> dataTotalList(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody BalanceListParam param, BindingResult result) {

        BaseRet<PageInfo<List<DataTotalRet>>> ret = new BaseRet<PageInfo<List<DataTotalRet>>>();

        PageInfo<List<DataTotalRet>> pageInfo = new PageInfo<List<DataTotalRet>>();

        try {

            checkParam(result);

            String startTime = "";
            String endTime = "";

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                startTime = param.getStartTime() + " 00:00:00";
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                endTime = param.getEndTime() + " 23:59:59";
            }

            int count = iDataTotalService.selectByCount(startTime, endTime);
            pageInfo.setCount(count);

            List<LpDataTotalTbl> list = iDataTotalService.selectByPage(param.getStart(), param.getPageSize(), startTime, endTime);

            if (list != null && list.size() > 0) {

                List<DataTotalRet> listRet = DozerMapperUtil.mapList(list, DataTotalRet.class);
                pageInfo.setRecords(listRet);
            }

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(pageInfo);


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }

    @RequestMapping(value = "/dataTotalSum", method = RequestMethod.POST)
    @ApiOperation(notes = "收入总计", httpMethod = "POST", value = "收入总计")
    public BaseRet<BigDecimal> dataTotalSum(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody BalanceListParam param, BindingResult result) {

        BaseRet<BigDecimal> ret = new BaseRet<BigDecimal>();

        try {

            checkParam(result);

            String startTime = "";
            String endTime = "";

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                startTime = param.getStartTime() + " 00:00:00";
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                endTime = param.getEndTime() + " 23:59:59";
            }

            BigDecimal sum = iDataTotalService.incomeSum(startTime, endTime);

            ret.setMsg("查询成功");
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setData(sum);


        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/storeDataTotal", method = RequestMethod.GET)
    @ApiOperation(notes = "门店数据统计（定时任务调用）", httpMethod = "GET", value = "门店数据统计（定时任务调用）")
    public BaseRet<String> storeDataTotal(@ApiParam(value = "请求参数", required = true) @RequestParam String setTime) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            //获取当前时间
            String time = CommonFunctionUtil.getStringTime(Constant.formatType.date);

            if (StringUtils.isNotEmpty(setTime)) {
                time = setTime;
            }

            String startTime = time + " 00:00:00";
            String endTime = time + " 23:59:59";

            //查询门店列表
            List<LpStoreTbl> storeList = iStoreService.selectList();

            List<LpStoreDataTotalTbl> dataList = new ArrayList<LpStoreDataTotalTbl>();

            for (LpStoreTbl value : storeList) {

                int storeId = value.getId();

                List<Integer> storeIdList = new ArrayList<Integer>();
                storeIdList.add(storeId);

                //总入场（需要门店）
                BigDecimal enterTotal = iDataTotalService.selectEnterTotal(startTime, endTime, storeId);
                //次卡入场（需要门店）
                BigDecimal DayCardEnterTotal = iDataTotalService.selectDayCardEnterTotal(startTime, endTime, storeId);
                //月卡入场（需要门店）
                BigDecimal MonthCardEnterTotal = iDataTotalService.selectMonthCardEnterTotal(startTime, endTime, storeId);
                //优惠劵入场（需要门店）
                BigDecimal CouponEnterTotal = iDataTotalService.selectCouponEnterTotal(startTime, endTime, storeId);
                //总收入（需要门店）
                //BigDecimal income = iDataTotalService.selectIncome(startTime, endTime, storeIdList);
                //次卡收入（需要门店）
                BigDecimal DayCardIncome = iDataTotalService.selectDayCardIncome(startTime, endTime, storeId);
                //月卡收入
                BigDecimal monthCardIncome = iDataTotalService.selectStoreMonthCardIncome(startTime, endTime, storeId);
                //充值收入
                BigDecimal rechargeIncome = iDataTotalService.selectStoreRechargeIncome(startTime, endTime, storeId);
                //月卡张数
                int monthCardNum = iDataTotalService.selectStoreMonthCardNum(startTime, endTime, storeId);
                //次卡张数
                int dayCardNum = iDataTotalService.selectStoreDayCardNum(startTime, endTime, storeId);


                LpStoreDataTotalTbl lpStoreDataTotalTbl = new LpStoreDataTotalTbl();
                lpStoreDataTotalTbl.setEnterTotal(enterTotal);
                lpStoreDataTotalTbl.setDaycardEnterTotal(DayCardEnterTotal);
                lpStoreDataTotalTbl.setMonthcardEnterTotal(MonthCardEnterTotal);
                lpStoreDataTotalTbl.setCouponEnterTotal(CouponEnterTotal);
                lpStoreDataTotalTbl.setDaycardIncome(DayCardIncome);
                lpStoreDataTotalTbl.setStoreId(storeId);
                lpStoreDataTotalTbl.setTimes(CommonFunctionUtil.changeTimeDate(time, Constant.formatType.date));
                lpStoreDataTotalTbl.setInsertTime(CommonFunctionUtil.getDateTime(Constant.formatType.second));
                lpStoreDataTotalTbl.setMonthcardIncome(monthCardIncome);
                lpStoreDataTotalTbl.setRechargeIncome(rechargeIncome);
                lpStoreDataTotalTbl.setIncome(DayCardIncome.add(monthCardIncome).add(rechargeIncome));
                lpStoreDataTotalTbl.setMonthcardNum(monthCardNum);
                lpStoreDataTotalTbl.setDaycardNum(dayCardNum);

                dataList.add(lpStoreDataTotalTbl);

            }

            //删除原有数据
            iDataTotalService.delStoreDataTotal(CommonFunctionUtil.changeTimeDate(startTime, Constant.formatType.second), CommonFunctionUtil.changeTimeDate(endTime, Constant.formatType.second));

            //写入数据
            iDataTotalService.insertStoreDataTotal(dataList);

            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("写入成功");

            //检查买了月卡没关联门店的用户
            this.setNotStoreIdUser();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    /**
     * 没有记录购卡门店的用户设置默认最近去过的门店
     */
    private void setNotStoreIdUser() {

        List<LpUserInfoTbl> list = iUserService.selectNotStoreId();

        if (list != null && list.size() > 0) {

            for (LpUserInfoTbl value : list) {

                //查询用户入场记录
                List<LpEquipmentLogsTbl> useLog = iDeviceService.selectEquipmentLogsByUser(value.getId());
                if (useLog != null && useLog.size() > 0) {

                    //最近入场的门店id
                    int storeId = useLog.get(0).getStoreId();
                    com.alibaba.fastjson.JSONObject ext = new com.alibaba.fastjson.JSONObject();
                    if (StringUtils.isNotEmpty(value.getExt())) {

                        ext = com.alibaba.fastjson.JSONObject.parseObject(value.getExt());
                        ext.put("reg_store", storeId);
                        ext.put("cart_store", storeId);

                    } else {
                        ext.put("reg_store", storeId);
                        ext.put("cart_store", storeId);
                    }

                    LpUserInfoTbl lpUserInfoTbl = new LpUserInfoTbl();
                    lpUserInfoTbl.setId(value.getId());
                    lpUserInfoTbl.setExt(ext.toJSONString());
                    iUserService.updateUserInfo(lpUserInfoTbl);

                }
            }
        }
    }


    @RequestMapping(value = "/zhimaAccreditCallRefound", method = RequestMethod.POST)
    @ApiOperation(notes = "芝麻信用押金解冻", httpMethod = "POST", value = "芝麻信用押金解冻")
    public BaseRet<String> zhimaAccreditCallRefound(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody ActionLibraryInfoParam param, BindingResult result) {

        BaseRet<String> ret = new BaseRet<String>();

        try {

            checkParam(result);

            LpOrderformTbl orderInfo = iFinanceService.selectOrderInfo(param.getId());

            if (orderInfo.getState().equals("2")) {

                List<LpZhimaAccreditCallBackTbl> zhimaInfo = iFinanceService.selectZhimaAccreditCallBack(param.getId());

                if (!zhimaInfo.isEmpty()) {

                    AlipayFundAuthOrderUnfreezeResponse refoundResult = AlipayUtil.fundAuthOrderUnFreeze(zhimaInfo.get(0).getAuthNo(), zhimaInfo.get(0).getOutRequestNo(), zhimaInfo.get(0).getAmount(), "守约成功， 解冻押金");

                    if (refoundResult.getMsg().equals("Success")) {

                        LpOrderformTbl lpOrderformTbl = new LpOrderformTbl();
                        lpOrderformTbl.setId(param.getId());
                        lpOrderformTbl.setState("7");

                        iFinanceService.updateOrder(lpOrderformTbl);

                        //更新用户押金信息
                        LpUserPropertyTbl lpUserPropertyTbl = new LpUserPropertyTbl();
                        lpUserPropertyTbl.setIsDepositFree("1");

                        iUserService.updateUserProperty(lpUserPropertyTbl, orderInfo.getUserId());

                        ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
                        ret.setMsg("退款成功");

                    } else {
                        ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
                        ret.setMsg(refoundResult.getMsg());
                    }

                } else {

                    ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                    ret.setMsg("订单不存在");
                }

            } else {
                ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
                ret.setMsg("已退款");
            }

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/searchBuyCardOrReachargeTotal", method = RequestMethod.POST)
    @ApiOperation(notes = "查询月卡/次卡购买总数和充值总计", httpMethod = "POST", value = "查询月卡/次卡购买总数和充值总计")
    public BaseRet<SearchBuyCardOrReachargeTotalRet> searchBuyCardOrReachargeTotal(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SearchBuyCardTotalParam param, BindingResult result) {

        BaseRet<SearchBuyCardOrReachargeTotalRet> ret = new BaseRet<SearchBuyCardOrReachargeTotalRet>();

        try {

            checkParam(result);

            String startTime = "";
            String endTime = "";

            if (StringUtils.isNotEmpty(param.getStartTime())) {
                startTime = param.getStartTime() + " 00:00:00";
            }

            if (StringUtils.isNotEmpty(param.getEndTime())) {
                endTime = param.getEndTime() + " 23:59:59";
            }

            SearchBuyCardOrReachargeTotalRet searchBuyCardOrReachargeTotalRet = new SearchBuyCardOrReachargeTotalRet();

            //查询月卡
            int monthCard = iFinanceService.selectBuyCardTotal(Integer.parseInt(Constant.goodsType.monthCard), startTime, endTime);
            int dayCard = iFinanceService.selectBuyCardTotal(Integer.parseInt(Constant.goodsType.dayCard), startTime, endTime);
            BigDecimal recharge = iFinanceService.selectReachargeTotal(startTime, endTime);

            searchBuyCardOrReachargeTotalRet.setDayCard(dayCard);
            searchBuyCardOrReachargeTotalRet.setMonthCard(monthCard);
            searchBuyCardOrReachargeTotalRet.setReacharge(recharge);

            ret.setData(searchBuyCardOrReachargeTotalRet);
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("查询成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/searchStoreIncomeInfo", method = RequestMethod.POST)
    @ApiOperation(notes = "查询门店收入明细", httpMethod = "POST", value = "查询门店收入明细")
    public BaseRet<List<SearchStoreIncomeInfoBaseRet>> searchStoreIncomeInfo(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SearchStoreIncomeInfoParam param, BindingResult result) {

        BaseRet<List<SearchStoreIncomeInfoBaseRet>> ret = new BaseRet<List<SearchStoreIncomeInfoBaseRet>>();

        try {

            checkParam(result);

            String startTime = param.getYear() + "-" + param.getMonth() + "-01 00:00:00";
            //计算结束日期
            String endTime = CommonFunctionUtil.getLastDayOfMonth(param.getYear(), param.getMonth()) + " 23:59:59";

            List<SelectStoreIncomeInfoDto> list = iDataTotalService.selectStoreIncomeInfo(startTime, endTime);

            List<SearchStoreIncomeInfoBaseRet> listRet = new ArrayList<SearchStoreIncomeInfoBaseRet>();

            if (list != null && list.size() > 0) {

                for (SelectStoreIncomeInfoDto value : list) {
                    SearchStoreIncomeInfoBaseRet searchStoreIncomeInfoBaseRet = new SearchStoreIncomeInfoBaseRet();
                    List<SearchStoreIncomeInfoRet> child = new ArrayList<SearchStoreIncomeInfoRet>();
                    searchStoreIncomeInfoBaseRet.setStoreName(value.getStoreName());

                    String[] times = value.getTimes().split(",");
                    String[] monthCardNum = value.getMonthCardNum().split(",");
                    String[] dayCardNum = value.getDayCardNum().split(",");
                    String[] monthCardIncome = value.getMonthCardIncome().split(",");
                    String[] dayCardIncome = value.getDayCardIncome().split(",");
                    String[] rechargeIncome = value.getRechargeIncome().split(",");
                    String[] income = value.getIncome().split(",");

                    for (int i = 0; i < times.length; i++) {
                        SearchStoreIncomeInfoRet searchStoreIncomeInfoRet = new SearchStoreIncomeInfoRet();
                        searchStoreIncomeInfoRet.setTimes(times[i]);
                        searchStoreIncomeInfoRet.setMonthCardNum(monthCardNum[i]);
                        searchStoreIncomeInfoRet.setDayCardNum(dayCardNum[i]);
                        searchStoreIncomeInfoRet.setMonthCardPrice(monthCardIncome[i]);
                        searchStoreIncomeInfoRet.setDayCardPrice(dayCardIncome[i]);
                        searchStoreIncomeInfoRet.setRechargePrice(rechargeIncome[i]);
                        searchStoreIncomeInfoRet.setTotalPrice(income[i]);
                        child.add(searchStoreIncomeInfoRet);
                    }

                    searchStoreIncomeInfoBaseRet.setList(child);
                    listRet.add(searchStoreIncomeInfoBaseRet);

                }
            }

            ret.setData(listRet);
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("查询成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }


    @RequestMapping(value = "/searchStoreEnterInfo", method = RequestMethod.POST)
    @ApiOperation(notes = "查询门店入场次数明细", httpMethod = "POST", value = "查询门店入场次数明细")
    public BaseRet<List<SearchStoreEnterInfoBaseRet>> searchStoreEnterInfo(@ApiParam(value = "请求参数", required = true) @Valid @RequestBody SearchStoreIncomeInfoParam param, BindingResult result) {

        BaseRet<List<SearchStoreEnterInfoBaseRet>> ret = new BaseRet<List<SearchStoreEnterInfoBaseRet>>();

        try {

            checkParam(result);

            String startTime = param.getYear() + "-" + param.getMonth() + "-01 00:00:00";
            //计算结束日期
            String endTime = CommonFunctionUtil.getLastDayOfMonth(param.getYear(), param.getMonth()) + " 23:59:59";

            List<SearchStoreEnterInfoBaseRet> listRet = new ArrayList<SearchStoreEnterInfoBaseRet>();

            List<SelectStoreEnterInfoDto> list = iDataTotalService.selectStoreEnterInfo(startTime, endTime);

            if (list != null && list.size() > 0) {

                for (SelectStoreEnterInfoDto value : list) {

                    SearchStoreEnterInfoBaseRet searchStoreEnterInfoBaseRet = new SearchStoreEnterInfoBaseRet();
                    searchStoreEnterInfoBaseRet.setStoreName(value.getStoreName());

                    List<SearchStoreEnterInfoRet> child = new ArrayList<SearchStoreEnterInfoRet>();

                    String[] times = value.getTimes().split(",");
                    String[] enterTotal = value.getEnterTotal().split(",");

                    for (int i = 0; i < times.length; i++) {

                        SearchStoreEnterInfoRet searchStoreEnterInfoRet = new SearchStoreEnterInfoRet();
                        searchStoreEnterInfoRet.setTimes(times[i]);
                        searchStoreEnterInfoRet.setNum(enterTotal[i]);
                        child.add(searchStoreEnterInfoRet);

                    }

                    searchStoreEnterInfoBaseRet.setList(child);
                    listRet.add(searchStoreEnterInfoBaseRet);

                }

            }

            ret.setData(listRet);
            ret.setCode(ApiResponseEnum.API_RESPONSE_SUCCESS);
            ret.setMsg("查询成功");

        } catch (Exception e) {
            log.error(e.getMessage(), e);
            ret.setCode(ApiResponseEnum.API_RESPONSE_ERROR);
            ret.setMsg(e.getMessage());
        }

        return ret;
    }

}
